layui.use([ 'form', 'table' , 'upload', 'element'], function() {
	var form = layui.form;
	var table = layui.table;
	var upload = layui.upload;
	var element = layui.element;
	var projectIdStr;
	var $ = layui.$;
	var active = {
		    reload: function(){
			      var nameText = $('#nameText');
			      var numberText = $("#numberText");
			      //执行重载
			      table.reload('projectTableReload', {
			        page: {
			          curr: 1 //重新从第 1 页开始
			        }
			        ,where: {
			            projectName: nameText.val(),
			            projectNumber: numberText.val(),
			        }
			      });
			    }
		};
	
	//监听用户名的输入框
	$('#nameText').on("input propertychange", function() {
        active.reload();
    });
    
	//监听姓名的输入框
    $('#numberText').on("input propertychange", function() {
        active.reload();
    });
    
    var roleId = "";
	$.ajax({
		type: 'post',
	    url: '../../sysuser/findUserRole',
	    async: false,
	    success: function(result){
	        roleId = result.role_id;
	        if(roleId == 4){
	        	$('#addProject').css('display','inline-block');//4代表项目管理员角色，只有项目管理员才能新建项目
	        }
	    }		
	});
	

	$("#formPlatSelectId").empty('');
	var url = "../../plat/findPlatByConditions";
	$.get(url, function(result) {
		var plat = result.data;
		var formPlatSelectId = $("#formPlatSelectId");
		$.each(plat, function(index, data) {
			var deptOption = $("<option value='" + data.id + "'>" + data.name + "</option>");
			formPlatSelectId.append(deptOption);
		});
		form.render('select');
	});
	
	var btn = document.getElementById("addProject");  
    btn.onclick =function(){  
		layer.open({
			type:1,
			title : "添加项目",
			skin : "editFile",
			area : [ "45%" ],
			btnAlign: 'c',
			btn : [ '添加项目' ,"取消"],				
			content : $("#addProjectDiv"),
			success : function(layero) {
				$('#projectNameInput').val("");//清空输入框
				$('#projectNumberInput').val("");//清空输入框
			},
			yes : function(index, layero) {
				var exsit = false;
				var projectNameInput = $('#projectNameInput').val();
				var projectNumberInput = $('#projectNumberInput').val();
				var platId = $('#formPlatSelectId option:selected').val();
				if(projectNameInput==""){
					layer.msg("项目名称不能为空");
					return false;
				}
				if(projectNumberInput==""){
					layer.msg("项目编号不能为空");
					return false;
				}		
				$.ajax({
					type : "POST",// 方法类型
					dataType : "json",// 预期服务器返回的数据类型
					url : "../../project/isProjectNameExist",// url
					data : {projectName:projectNameInput,
						    projectNumber : projectNumberInput,},
					async:false,
					success : function(result) {
					    if(result.data=="1"){
					    	layer.msg("项目名称或编号已存在");
					    	exsit = true;
					    }else if(result.data=="2"){
					    	layer.msg("判断项目名称和编号是否已存在时出错");
					    	exsit = true;
					    }
					}						
				});
				if(exsit){
					return false;
				}
				$.ajax({
					type : "POST",// 方法类型
					dataType : "json",// 预期服务器返回的数据类型
					url : "../../project/addProject",// url
					data : {
						projectName : projectNameInput,
						projectNumber : projectNumberInput,
						platId : platId
					},
					success : function(result) {
						if (result.code == 0) {
							layer.close(index);
							layer.msg('新增项目成功');
							table.reload('projectTableReload');
						}else{
							layer.msg('新增项目失败');
							layer.close(index);
						}
					},
					error : function() {
						layer.msg('新增项目失败');
						layer.close(index);
					}
				});
			}	
		});
    }
	
	table.render({
		elem : '#projectTable',
		url : '../../project/findProjectByConditions',
		toolbar : '#toolbarProject',
		title : '任务表',
		cols : [ [ 
				{type : 'checkbox', fixed: 'left'},
		    	{field: 'id',title: 'ID',sort: true, fixed: 'left'},
		    	{field: 'projectName',title: '项目名称'},
		    	{field: 'projectNumber',title: '项目编号'},
		    	{field: 'paltName' , title:'关联平台'},
		    	{fixed : 'right',title : '操作',width :roleId=="4" ? 200 : 100, templet:function(d){
		    		if(roleId=="4"){
		    			return "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='details' style='margin-left: 15px'>详情</a>"
			            +  "<a class='layui-btn layui-btn-danger layui-btn-xs' lay-event='del' style=''margin-left: 15px'>删除</a>"
			           + "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='upd' style='margin-left: 15px'>编辑</a>"; 
		    		}else{
		    			return "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='details' style='margin-left: 15px'>详情</a>";
		    		}		    		
		    	}}
	           ] ],
        page: true,
	    height: $(window).height() -50,
	    id: 'projectTableReload',
	});
	
	// 头工具栏事件
	table.on('toolbar(projectTable)', function(obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
		case 'getCheckData':
			var data = checkStatus.data;
			layer.alert(JSON.stringify(data));
			break;
		case 'getCheckLength':
			var data = checkStatus.data;
			layer.msg('选中了：' + data.length + ' 个');
			break;
		case 'isAll':
			layer.msg(checkStatus.isAll ? '全选' : '未全选');
			break;
		case 'addProject':
			
			break;
		}
	});
	
	//监听行工具事件
	table.on('tool(projectTable)', function(obj) {
		var data = obj.data;
		projectIdStr = data.id
		if (obj.event === 'details') {
			 table.reload('projectProcessInstanceTableReload',{
					where: { //设定异步数据接口的额外参数，任意设
						projectId: data.id,
						type : '2'
					  }
			 });
			 layer.open({
					type : 1,
					title : "项目版本列表",
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%", "70%"],
					content : $("#projectProcessInstanceTableDiv") 
				});	
		} else if (obj.event === 'del') {	
			layer.confirm('确认删除此项目?', function(index){
				$.ajax({
					type : "POST",// 方法类型
					dataType : "json",// 预期服务器返回的数据类型
					url : "../../project/deleteProject",// url
					data : {
						projectId : data.id,
					},
					success : function(result) {
						if (result.code == 0) {
							table.reload('projectTableReload');
							layer.msg('删除项目成功');
						}else{
							layer.msg('删除项目失败');
							layer.close(index);
						}
					},
					error : function() {
						layer.msg('删除项目失败');
						layer.close(index);
					}
				});
				  layer.close(index);
			});  
			
		} else if (obj.event === 'upd') {	
	        layer.open({
				type:1,
				title : "编辑项目",
				skin : "editFile",
				area : [ "45%" ],
				btnAlign: 'c',
				btn : [ '确认' ,"取消"],				
				content : $("#addProjectDiv"),
				success : function() {
					$('#projectNameInput').val(data.projectName);
					$('#projectNumberInput').val(data.projectNumber);
					$('#formPlatSelectId').val(data.platId);
					form.render('select');
				},
				yes : function(index, layero) {
					var projectNameInput = $('#projectNameInput').val();
					var projectNumberInput = $('#projectNumberInput').val();
					var formPlatSelectId = $('#formPlatSelectId option:selected').val();
					if(projectNameInput==""){
						layer.msg("项目名称不能为空");
						return false;
					}
					if(projectNumberInput==""){
						layer.msg("醒目编号不能为空");
						return false;
					}
					$.ajax({
						type : "POST",// 方法类型
						dataType : "json",// 预期服务器返回的数据类型
						url : "../../project/updateProjectById",// url
						data : {
							projectId : data.id,
							projectName : projectNameInput,
							projectNumber : projectNumberInput,
							plattSelect : formPlatSelectId
						},
						success : function(result) {
							layer.close(index);
							layer.msg(result.msg);
							table.reload('projectTableReload');
						},
						error : function() {
							layer.msg('编辑项目失败');
							layer.close(index);
						}
					});
				}	
			});
		}
	});
	
	table.render({
		elem : '#projectProcessInstanceTable',
		url : '../../project/findProcessInstanceByprojectId',
		title : '项目程序文件列表',
		cols : [ [ 
				//{type : 'checkbox', fixed: 'left'},
		    	{field: 'processInstanceId',title: '流程编号',sort: true, fixed: 'left',width : 100},
		    	{field: 'name',title: '流程名称'},
		    	{field: 'version',title: '版本号'},
		    	{fixed : 'right', title : '操作', toolbar : '#barProjectProcessInstance', width : 125}
	           ] ],
        page: false,
	    id: 'projectProcessInstanceTableReload',
	});
	
	//监听行工具事件
	table.on('tool(projectProcessInstanceTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'details') {
			 table.reload('projectProcessInstanceFileTableReload',{
					where: { //设定异步数据接口的额外参数，任意设
						processInstanceId: data.processInstanceId
					  }
			 });
			 layer.open({
					type : 1,
					title : "文件列表",
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%","80%"],
					content : $("#projectProcessInstanceFileTableDiv") 
				});	
		} else if (obj.event === 'attachments') {	
			table.reload('attachmentsTableReload',{
				where: { //设定异步数据接口的额外参数，任意设
					processInstanceId : data.processInstanceId
				  }
			 });
			 layer.open({
					type : 1,
					title : "附件文件列表",
					offset: '100px',
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%", "80%"],
					//maxWidth: 1000,
					//maxHeight: $(window).height()*0.8,
					content : $("#attachmentsTableDiv") 
				});	
		}
	});
	
	table.render({
		elem : '#projectProcessInstanceFileTable',
		url : '../../plat/findPlatProcessInstanceFileTableByPid',//这里的名字虽然是plat,但是sql方法是plat和project的流程都可以使用
		title : '项目程序文件列表',
		cols : [ [ 
				//{type : 'checkbox', fixed: 'left'},
		    	{field: 'id',title: 'ID',sort: true, fixed: 'left',width : 75},
		    	{field: 'fileName',title: '文件名称'},
		    	{field: 'time',title: '更新时间',sort: true,templet:function(d){return datetimeFormat(d.time)},width : 200},
		    	{field: 'status',title: '释放状态',templet:function(d){return statusToChinese(d.status)}, width : 100},
		    	{field: 'name',title: '更新人',width : 100},
		    	{fixed : 'right', title : '操作', toolbar : '#barProcessInstanceFile', width : 150}
	           ] ],
        page: false,
	    id: 'projectProcessInstanceFileTableReload',
	});
	
	
	//监听行工具事件
	table.on('tool(projectProcessInstanceFileTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'version') {
			 table.reload('processInstanceFileHistTableReload',{
					where: { //设定异步数据接口的额外参数，任意设
						processInstanceFileId: data.id
					  }
			 });
			 layer.open({
					type : 1,
					title : "文件历史版本列表",
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%","80%"],
					content : $("#processInstanceFileHistTableDiv") 
				});	
		} else if (obj.event === 'attachments') {	
			table.reload('attachmentsTableReload',{
				where: { //设定异步数据接口的额外参数，任意设
					processInstanceId : data.processInstanceId
				  }
			 });
			 layer.open({
					type : 1,
					title : "附件文件列表",
					offset: '100px',
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%", "80%"],
					//maxWidth: 1000,
					//maxHeight: $(window).height()*0.8,
					content : $("#attachmentsTableDiv") 
				});	
		}else if (obj.event === 'downLoad'){
			 downLoadFile(data.fileName, data.url);
		}
	});
	
	
	table.render({
		elem : '#processInstanceFileHistTable',
		url : '../../project/findProcessInstanceFileHistTable',
		title : '文件历史版本列表',
		cols : [ [ 
				//{type : 'checkbox', fixed: 'left'},
		    	{field: 'filename',title: '文件名称'},
		    	{field: 'time',title: '更新时间',sort: true,templet:function(d){return datetimeFormat(d.time)},width : 200},
		    	{field: 'name',title: '更新人',width : 100},
		    	{fixed : 'right', title : '操作', toolbar : '#barProcessInstanceFileHist', width : 100}
	           ] ],
        page: false,
	    id: 'processInstanceFileHistTableReload',
	});
	
	//监听行工具事件
	table.on('tool(processInstanceFileHistTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'downLoad') {
			 downLoadFile(data.filename, data.url);
		}
	});
	
	
	table.render({
		elem : '#attachmentsTable',
		url : '../../project/findattachmentsTableByPid',
		title : '文件的附件',
		cols : [ [ 
				//{type : 'checkbox', fixed: 'left'},
		    	{field: 'name',title: '文件名称'},
		    	{field: 'time',title: '更新时间',sort: true,templet:function(d){return datetimeFormat(d.time)},width : 200},
		    	{field: 'description',title: '更新人',width : 100},
		    	{fixed : 'right', title : '操作', toolbar : '#barAttachments', width : 100}
	           ] ],
        page: false,
	    id: 'attachmentsTableReload',
	});
	
	//监听行工具事件
	table.on('tool(attachmentsTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'downLoad') {
			 downLoadFile(data.name, data.url);
		}
	});
	
	
	statusToChinese = function(status){
		if(status == "0"){
			return "未释放";
		}else{
			return "已释放";
		}
	}
	
	findProcessInstanceByType  = function(type){
		table.reload('projectProcessInstanceTableReload',{
			where: { //设定异步数据接口的额外参数，任意设
				projectId: projectIdStr,
				type : type
			  }
	 });	
	}
		
	downLoadMutilFilesToZip = function(){
		  var list = table.cache.processInstanceFileHistTableReload;
           var imgNameList = [];
           var imgUrlList = [];
           for(var i = 0;i<list.length;i++){    
	           imgNameList.push(list[i].filename); 
	           //压缩文件不允许重名，故有重名文件则改变名字        
               for(var j = 0; j < i; j++){
            	   if(list[i].filename == list[j].filename){
            		   imgNameList[i] = list[i].filename.substr(0,list[i].filename.indexOf(".")) + "_" +  i + list[i].filename.substr(list[i].filename.indexOf(".")) ;//文件名称
            		   break;
            	   }
               }
               imgUrlList.push(list[i].url);//文件绝对路径
           }
           var paths =  encodeURI(encodeURI(imgUrlList));
           var names = encodeURI(encodeURI(imgNameList));
           //将名称传入后台
           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
	}
	
	downLoadAttachmentsFilesToZip = function(){
		var list = table.cache.attachmentsTableReload;
		           var imgNameList = [];
		           var imgUrlList = [];
		           for(var i = 0;i<list.length;i++){    
			           imgNameList.push(list[i].name); 
			           //压缩文件不允许重名，故有重名文件则改变名字        
		               for(var j = 0; j < i; j++){
		            	   if(list[i].name == list[j].name){
		            		   imgNameList[i] = list[i].name.substr(0,list[i].name.indexOf(".")) + "_" +  i + list[i].name.substr(list[i].name.indexOf(".")) ;//文件名称
		            		   break;
		            	   }
		               }
		               imgUrlList.push(list[i].url);//文件绝对路径
		           }
		           var paths =  encodeURI(encodeURI(imgUrlList));
		           var names = encodeURI(encodeURI(imgNameList));
		           //将名称传入后台
		           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
	}

});